using JSOCTNet.Core.Utility;
using JSOCTNet.IBIZ;
using JSOCTNet.IDAL;
using JSOCTNetSDK.XmppModel;
using JSOCTNetSDK.XmppModelFun;
using JSOCTNetSDK.XmppTaskModel;
using JSST.Framework.CopyRight;
using jsxmpp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;

namespace JSOCTNetSDK.XmppTask
{
	public class TaskManage : IXmppDown
	{
		private static TaskManage m_Manage;

		private System.Collections.Generic.List<TaskBase> m_TaskAllList = new System.Collections.Generic.List<TaskBase>();

		private System.Collections.Generic.List<TaskBase> TaskDownList = new System.Collections.Generic.List<TaskBase>();

		public System.Collections.Generic.List<TaskBase> TaskUpList = new System.Collections.Generic.List<TaskBase>();

		public System.Collections.Generic.List<TaskBase> TaskUpHistoryList = new System.Collections.Generic.List<TaskBase>();

		private BackgroundWorker m_BackWorkerUpData = new BackgroundWorker();

		private BackgroundWorker m_BackWorkerUpFile = new BackgroundWorker();

		private BackgroundWorker m_BackWorkerUpOther = new BackgroundWorker();

		private bool m_BackWorkerUpDataIsBusy;

		private bool m_BackWorkerUpFileIsBusy;

		private bool m_BackWorkerUpOtherIsBusy;

		private System.Collections.Generic.List<ISyncTask> m_ISyncTaskList = new System.Collections.Generic.List<ISyncTask>();

		private System.Collections.Generic.List<IXmppSend> iXmppSendList = new System.Collections.Generic.List<IXmppSend>();

		public static TaskManage Instance
		{
			get
			{
				if (TaskManage.m_Manage == null)
				{
					TaskManage.m_Manage = new TaskManage();
					TaskManage.m_Manage.LoadTask();
					TaskManage.m_Manage.InitializeBackgroundWorker();
				}
				return TaskManage.m_Manage;
			}
		}

		private void InitializeBackgroundWorker()
		{
			this.m_BackWorkerUpData.WorkerSupportsCancellation = true;
			this.m_BackWorkerUpData.DoWork += new DoWorkEventHandler(this.m_BackWorkerUpData_DoWork);
			this.m_BackWorkerUpFile.WorkerSupportsCancellation = true;
			this.m_BackWorkerUpFile.DoWork += new DoWorkEventHandler(this.m_BackWorkerUpFile_DoWork);
			this.m_BackWorkerUpOther.WorkerSupportsCancellation = true;
			this.m_BackWorkerUpOther.DoWork += new DoWorkEventHandler(this.m_BackWorkerUpOther_DoWork);
		}

		private void m_BackWorkerUpOther_DoWork(object sender, DoWorkEventArgs e)
		{
			this.m_BackWorkerUpOtherIsBusy = true;
			try
			{
				foreach (JSOCTNetSDK.XmppTaskModel.TaskInfo current in this.TaskUpList)
				{
					JSOCTNet.IBIZ.FactorySync.CreateSyncData();
					ISyncTask syncTask = JSOCTNet.IBIZ.FactorySync.CreateSyncTask(current.ClassName);
					if (syncTask != null)
					{
						this.m_ISyncTaskList.Add(syncTask);
						syncTask.Init(current);
					}
				}
				goto IL_E4;
			}
			catch (System.Exception ex)
			{
				XmppLogHelper.LogSDK.Error("Xmpp主动上传任务加载失败", ex);
				goto IL_E4;
			}
			IL_77:
			foreach (ISyncTask current2 in this.m_ISyncTaskList)
			{
				if (this.m_BackWorkerUpOther.CancellationPending)
				{
					this.m_BackWorkerUpOtherIsBusy = false;
					return;
				}
				try
				{
					current2.Execute();
				}
				catch (System.Exception ex2)
				{
					XmppLogHelper.LogSDK.Error("Xmpp主动上传任务执行失败", ex2);
				}
			}
			System.Threading.Thread.Sleep(10000);
			IL_E4:
			if (!this.m_BackWorkerUpOther.CancellationPending)
			{
				goto IL_77;
			}
			this.m_BackWorkerUpOtherIsBusy = false;
		}

		private void m_BackWorkerUpFile_DoWork(object sender, DoWorkEventArgs e)
		{
			this.m_BackWorkerUpFileIsBusy = true;
			while (!this.m_BackWorkerUpFile.CancellationPending)
			{
				JSOCTNet.IDAL.ISyncData syncData = null;
				System.Collections.Generic.List<SyncDataBase> list = new System.Collections.Generic.List<SyncDataBase>();
				try
				{
					syncData = JSOCTNet.IDAL.FactorySync.CreateSyncData();
					list = syncData.GetSyncFile();
				}
				catch (System.Exception ex)
				{
					XmppLogHelper.LogSDK.Info("获取中间表数据报错,主动上传数据任务推出", ex);
					return;
				}
				int i = 0;
				while (i < list.Count)
				{
					if (this.m_BackWorkerUpFile.CancellationPending)
					{
						this.m_BackWorkerUpFileIsBusy = false;
						return;
					}
					SyncDataBase syncDataBase = list[i];
					FileDescription fileDescription = new FileDescription();
					try
					{
						JsonToModel.GetModel(syncDataBase.JsonStr, ref fileDescription);
						bool flag = false;
						if ((syncDataBase.OptDate.AddMinutes(2.0) < System.DateTime.Now && syncDataBase.BizFailCount < 3) || syncDataBase.OptDate.AddMinutes(10.0) < System.DateTime.Now)
						{
							if (fun.FileExist(fileDescription.fileName))
							{
								System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileDescription.fileName);
								fileDescription.fileSize = (int)fileInfo.Length;
								bool flag2 = false;
								foreach (IXmppSend current in this.iXmppSendList)
								{
									flag2 = current.IsXmppConnOK();
								}
								if (flag2)
								{
									foreach (IXmppSend current2 in this.iXmppSendList)
									{
										flag = current2.SendFile(fileDescription, 2);
									}
									XmppLogHelper.LogSDKUpdateData.Info("上传文件，路径：" + fileDescription.fileName + "----上传结果为：" + flag.ToString());
									if (flag)
									{
										syncDataBase.SeqID = fileDescription.uid;
										syncData.Delete(syncDataBase);
										i++;
									}
									else
									{
										syncData.Update(syncDataBase, false, true);
										if (syncDataBase.BizFailCount > 10)
										{
											syncData.Delete(syncDataBase);
										}
										i++;
									}
									System.Threading.Thread.Sleep(JSOCTNetSDK.XmppModelFun.ConfigFile.FileUploadInterval);
								}
								else
								{
									XmppLogHelper.LogSDKUpdateData.Info(string.Format("连接【{0}】失败，正在尝试重新连接....", JSOCTNetSDK.XmppModelFun.ConfigFile.JIDFileUpload));
									System.Threading.Thread.Sleep(10000);
								}
							}
							else
							{
								XmppLogHelper.LogSDKUpdateData.Info("上传文件不存在，路径：" + fileDescription.fileName);
								if (syncDataBase.BizFailCount > 10)
								{
									syncData.Delete(syncDataBase);
								}
								else
								{
									syncData.Update(syncDataBase, false, true);
								}
								i++;
								System.Threading.Thread.Sleep(5000);
							}
						}
						else
						{
							i++;
							System.Threading.Thread.Sleep(1);
						}
					}
					catch (System.Exception ex2)
					{
						XmppLogHelper.LogSDKUpdateData.Error("传输业务图片任务报错", ex2);
						syncData.Update(syncDataBase, true, false);
						System.Threading.Thread.Sleep(10000);
					}
				}
				System.Threading.Thread.Sleep(10000);
			}
			this.m_BackWorkerUpFileIsBusy = false;
		}

		private void m_BackWorkerUpData_DoWork(object sender, DoWorkEventArgs e)
		{
			this.m_BackWorkerUpDataIsBusy = true;
			while (!this.m_BackWorkerUpData.CancellationPending)
			{
				JSOCTNet.IDAL.ISyncData syncData = null;
				System.Collections.Generic.List<SyncDataBase> list = new System.Collections.Generic.List<SyncDataBase>();
				try
				{
					syncData = JSOCTNet.IDAL.FactorySync.CreateSyncData();
					list = syncData.GetSyncData();
				}
				catch (System.Exception ex)
				{
					XmppLogHelper.LogSDK.Info("获取中间表数据报错,主动上传数据任务退出", ex);
					return;
				}
				int i = 0;
				while (i < list.Count)
				{
					if (this.m_BackWorkerUpData.CancellationPending)
					{
						this.m_BackWorkerUpDataIsBusy = false;
						return;
					}
					SyncDataBase syncDataBase = list[i];
					ServiceRequestParam serviceRequestParam = new ServiceRequestParam();
					ServiceResponseData serviceResponseData = null;
					try
					{
						JsonToModel.GetModel(syncDataBase.JsonStr, ref serviceRequestParam);
						foreach (IXmppSend current in this.iXmppSendList)
						{
							serviceResponseData = current.requestService(serviceRequestParam, serviceRequestParam.serviceId, "", syncDataBase.InterfaceName);
						}
						if (serviceResponseData.resultCode == 0)
						{
							syncDataBase.SeqID = serviceRequestParam.seqId;
							syncData.Delete(syncDataBase);
							i++;
						}
						else if (serviceResponseData.resultCode == 1)
						{
							syncData.Update(syncDataBase, false, true);
							if (syncDataBase.BizFailCount > 10)
							{
								syncDataBase.SeqID = serviceRequestParam.seqId;
								syncData.Delete(syncDataBase);
							}
							i++;
						}
						else
						{
							syncData.Update(syncDataBase, true, false);
							System.Threading.Thread.Sleep(10000);
						}
						System.Threading.Thread.Sleep(100);
					}
					catch (System.Exception ex2)
					{
						XmppLogHelper.LogSDKUpdateData.Info("传输业务数据任务报错", ex2);
						syncData.Update(syncDataBase, true, false);
						System.Threading.Thread.Sleep(10000);
					}
				}
				System.Threading.Thread.Sleep(2000);
			}
			this.m_BackWorkerUpDataIsBusy = false;
		}

		public void LoadTask()
		{
			this.TaskDownList.Clear();
			this.TaskUpList.Clear();
			this.TaskUpHistoryList.Clear();
			this.m_TaskAllList = TaskInfo.GetSyncList<TaskBase>("Sync.TaskInfo").ToList<TaskBase>();
			foreach (TaskBase current in this.m_TaskAllList)
			{
				if (current.Enable)
				{
					if (current.TaskUp && !string.IsNullOrWhiteSpace(current.DllPath))
					{
						this.TaskUpList.Add(current);
					}
					if (!string.IsNullOrEmpty(current.ClassName) && !string.IsNullOrEmpty(current.DllPath))
					{
						string path = System.AppDomain.CurrentDomain.BaseDirectory + current.DllPath;
						if (System.IO.File.Exists(path))
						{
							try
							{
								object obj = System.Reflection.Assembly.LoadFile(path).CreateInstance(current.ClassName);
								if (obj != null)
								{
									TaskBase taskBase = obj as TaskBase;
									if (taskBase != null)
									{
										taskBase.IsSyncData = current.IsSyncData;
										taskBase.IsCache = current.IsCache;
										taskBase.CacheTime = current.CacheTime;
										taskBase.CornStr = current.CornStr;
										taskBase.Enable = current.Enable;
										taskBase.Relyon = current.Relyon;
										taskBase.TaskCode = current.TaskCode;
										taskBase.ID = current.ID;
										taskBase.VersionID = current.VersionID;
										taskBase.TaskName = current.TaskName;
										taskBase.TaskType = current.TaskType;
										taskBase.ClassName = current.ClassName;
										taskBase.DllPath = current.DllPath;
										taskBase.StartTime = current.StartTime;
										if (current.TaskDown && !string.IsNullOrWhiteSpace(current.DllPath))
										{
											this.TaskDownList.Add(taskBase);
										}
										if (current.TaskUpHistory && !string.IsNullOrWhiteSpace(current.DllPath))
										{
											this.TaskUpHistoryList.Add(taskBase);
										}
										continue;
									}
								}
							}
							catch (System.Exception ex)
							{
								XmppLogHelper.LogSDK.Error("TaskManage 加载任务失败", ex);
							}
						}
					}
					if (current.TaskDown)
					{
						this.TaskDownList.Add(current);
					}
					if (current.TaskUpHistory)
					{
						this.TaskUpHistoryList.Add(current);
					}
				}
			}
		}

		public ServiceResponseData DownRequestProcess(ServiceRequestParam request)
		{
			ServiceResponseData serviceResponseData = new ServiceResponseData();
			TaskBase taskBase = this.TaskDownList.Find((TaskBase f) => f.TaskCode == request.serviceId);
			XmppLogHelper.LogSDKDownData.Info("接收下发数据：" + ModelToJson.GetJson(request));
			if (taskBase != null)
			{
				string text = string.Format("\n\n{0}【{1}】【{2}】{3}", new object[]
				{
					System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
					taskBase.TaskName,
					taskBase.TaskCode,
					"下发数据开始处理"
				});
				XmppLogHelper.LogSDKDownData.Info(text);
				try
				{
					serviceResponseData = taskBase.Down(request);
				}
				catch (System.Exception ex)
				{
					XmppLogHelper.LogSDKDownData.Error("执行下发任务失败！" + ModelToJson.GetJson(request), ex);
					serviceResponseData = null;
				}
				if (serviceResponseData != null)
				{
					text = string.Format(" {0}{1}", (serviceResponseData.resultCode == 0) ? "成功" : ("失败 " + serviceResponseData.message), System.Environment.NewLine);
					XmppLogHelper.LogSDKDownData.Info(text);
					if (taskBase.TaskCode.StartsWith("NISSP_JSPAY") && !taskBase.TaskCode.EndsWith("EQUIP"))
					{
						text += string.Format("返回结果\n{0}\n", serviceResponseData.dataItems[0].attributes["RESULT"].ToString());
						XmppLogHelper.LogSDKDownData.Info(text);
					}
				}
				else
				{
					text = string.Format("\n\n{0}【{1}】【{2}】{3}", new object[]
					{
						System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
						taskBase.TaskName,
						taskBase.TaskCode,
						"下发未收到响应数据，请分析原因并重试"
					});
					serviceResponseData = new ServiceResponseData();
					serviceResponseData.resultCode = 1;
					serviceResponseData.message = text;
					XmppLogHelper.LogSDKDownData.Error(text);
				}
				serviceResponseData.serviceId = request.serviceId;
				serviceResponseData.seqId = request.seqId;
			}
			else
			{
				string strMessage = string.Format("{0}【{1}】{2} {3}", new object[]
				{
					System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
					request.serviceId,
					"下发 任务未启用操作",
					System.Environment.NewLine
				});
				XmppLogHelper.LogSDKDownData.Error(strMessage);
			}
			return serviceResponseData;
		}

		public string HttpGet(string strUrl)
		{
			string text = "";
			try
			{
				XmppLogHelper.LogSDKHttp.Info("HttpGet请求地址：" + strUrl);
				HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(strUrl);
				HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
				System.IO.StreamReader streamReader = new System.IO.StreamReader(httpWebResponse.GetResponseStream(), System.Text.Encoding.UTF8);
				text = streamReader.ReadToEnd();
				streamReader.Close();
				XmppLogHelper.LogSDKHttp.Info("HttpGet请求返回数据：" + text);
			}
			catch (System.Exception ex)
			{
				string strMessage = "HttpGet请求错误：" + ex.ToString();
				XmppLogHelper.LogSDKHttp.Error(strMessage);
			}
			return text;
		}

		public string HttpPost(string strUrl, string strPostContent)
		{
			string text = "";
			try
			{
				XmppLogHelper.LogSDKHttp.Info("HttpPost请求地址：" + strUrl);
				XmppLogHelper.LogSDKHttp.Info("HttpPost请求参数：" + strPostContent);
				HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(strUrl);
				httpWebRequest.Method = "POST";
				httpWebRequest.ContentType = "application/x-www-form-urlencoded";
				byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strPostContent);
				httpWebRequest.ContentLength = (long)bytes.Length;
				System.IO.Stream requestStream = httpWebRequest.GetRequestStream();
				requestStream.Write(bytes, 0, bytes.Length);
				requestStream.Close();
				HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
				System.IO.StreamReader streamReader = new System.IO.StreamReader(httpWebResponse.GetResponseStream(), System.Text.Encoding.UTF8);
				text = streamReader.ReadToEnd();
				streamReader.Close();
				XmppLogHelper.LogSDKHttp.Info("HttpPost请求返回数据：" + text);
			}
			catch (System.Exception ex)
			{
				string strMessage = "HttpPost请求错误：" + ex.ToString();
				XmppLogHelper.LogSDKHttp.Error(strMessage);
			}
			return text;
		}

		public bool StartTask(System.Collections.Generic.List<IXmppSend> iXmppSendList)
		{
			if (iXmppSendList.Count == 0)
			{
				XmppLogHelper.LogSDK.Error("TaskManage 开始启动失败：没有可以执行上传任务的接口！");
				return false;
			}
			if (!this.CheckLicense())
			{
				string strMessage = "请检查License配置是否正确";
				XmppLogHelper.LogSDK.Info(strMessage);
				return false;
			}
			this.iXmppSendList = iXmppSendList;
			XmppLogHelper.LogSDK.Info("TaskManage 开始启动任务");
			if (!this.m_BackWorkerUpData.IsBusy)
			{
				this.m_BackWorkerUpData.RunWorkerAsync();
			}
			if (!this.m_BackWorkerUpFile.IsBusy)
			{
				this.m_BackWorkerUpFile.RunWorkerAsync();
			}
			if (!this.m_BackWorkerUpOther.IsBusy)
			{
				this.m_BackWorkerUpOther.RunWorkerAsync();
			}
			return true;
		}

		public void StopTask()
		{
			XmppLogHelper.LogSDK.Info("TaskManage 开始停止");
			this.m_BackWorkerUpData.CancelAsync();
			this.m_BackWorkerUpFile.CancelAsync();
			this.m_BackWorkerUpOther.CancelAsync();
			while (this.m_BackWorkerUpDataIsBusy || this.m_BackWorkerUpFileIsBusy || this.m_BackWorkerUpOtherIsBusy)
			{
				System.Threading.Thread.Sleep(1000);
			}
			XmppLogHelper.LogSDK.Info("TaskManage 停止结束");
		}

		public void UploadResultProcess(ServiceResponseData response)
		{
		}

		private bool CheckLicense()
		{
			bool flag = false;
			if (!JSOCTNetSDK.XmppModelFun.ConfigFile.License)
			{
				flag = true;
			}
			if (!flag)
			{
				CopyRightResponse copyRight = Check.Instance().GetCopyRight();
				if (copyRight.CopyRightResult == enumCopyRightResult.Success)
				{
					flag = true;
				}
			}
			return flag;
		}
	}
}
